$(document).ready(function () {
    initFenlei();
    init();
});

function update() {
    var fenleiids = $(".contenta").val();
    var id = $("input[name='id']").val();
    var content = $(".a").val();
    var name = $("input[name='name']").val();
    var price = $("input[name='price']").val();
    var stock = $("input[name='stock']").val();

    $.ajax({
        url: "/commodity/updateById",
        type: 'GET',
        data: {
            'id': id,
            'content': content,
            'name': name,
            'price': price,
            'stock': stock,
            'commodityFenlei': fenleiids
        },
        dataType: "JSON",
        traditional: true,
        async: false,
        success: function (res) {
            if (res.code == "201") {
                alert(res.msg);
            }
            window.location.href = "/commoditieView/" + res.data.id;
        },
        error: function (e) {
            alert('发生错误')
        }
    })
}

function initFenlei() {
    $.ajax({
        url: "/fenlei/findAll",
        type: 'GET',
        data: {},
        dataType: "JSON",
        async: false,
        success: function (res) {
            if (res.code === "200") {
                var data = res.data;
                var xlk = "";
                for (var i = 0; i < data.length; i++) {
                    xlk += "<option class='chosena' value=" + data[i].id + ">" + data[i].name + "</option>";

                }
                $("#contenta").html(xlk);
                $("#contenta").trigger("chosen:updated");

            } else {
                alert(res.msg)
            }

        },
        error: function (e) {
            alert('发生错误')
        }

    })
}

function init() {

    var path = location.href;
    var id = path.substring(path.lastIndexOf("/") + 1)

    $.ajax({
        url: "/commodity/ViewfindById",
        type: 'GET',
        data: {
            'id': id
        },
        dataType: "JSON",
        async: false,
        success: function (res) {
            if (res.code == "200") {
                var data = res.data;
                $(".id").val(data.id);
                $(".name").val(data.name);
                $(".price").val(data.price);
                $(".stock").val(data.stock);
                var fl = [];
                for (var i = 0; i < res.data2.length; i++) {
                    fl.push(res.data2[i].id);
                }
                $(".contenta").val(fl);
                $(".contenta").trigger("chosen:updated");
            } else {
                alert(res.msg);
            }
        },
        error: function (e) {
            alert('发生错误')
        }
    })
}